package com.ds;

import com.sun.syndication.io.*;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndEntryImpl;

import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.text.SimpleDateFormat;
import java.text.ParseException;

/**
 * Created by IntelliJ IDEA.
 * User: daniel
 * Date: 01/11/2009
 * Time: 17:16:24
 */
public class MyEpisodesView extends JList {

    private static final long serialVersionUID = -7907935586343685918L;

    private static final Pattern airDatePattern = Pattern.compile("\\[ ([0-9]{2}\\-[A-Za-z]{3}\\-[0-9]{4}) \\]");
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MMM-yyyy");
//    private static final Pattern DATE_PATTERN = Pattern.compile("(\\[[^\\]]+\\]){3}\\[ ([^ ]+) \\]");

//    private static final String rssURL = "http://myepisodes.com/rss.php?feed=mylist&uid=usernam&pwdmd5=hashcode&onlyunacquired=1";
    private String rssURL;// = "http://myepisodes.com/rss.php?feed=mylist&uid=username&pwdmd5=hashcode&onlyunacquired=1";
    private Calendar calendar = Calendar.getInstance();

//    private JFrame parent;
    private DefaultListModel model = new DefaultListModel();

    public MyEpisodesView(JFrame frame) {
//        this.parent = frame;
    }

    public void init() {
        try {
            model.removeAllElements();
            setCellRenderer(new EpisodeTitleCellRenderer());
            readSource();
            setModel(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void setRssURL(String rssURL) {
        this.rssURL = rssURL;
    }

    private void readSource() throws IOException, FeedException, ParseException {

        //set the calendar to the date of yesterday, to display yesterday's publish in different color
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        calendar.set(Calendar.HOUR,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,1);
        calendar.set(Calendar.MILLISECOND,1);
        calendar.set(Calendar.AM_PM,Calendar.AM);

        URL feedUrl = new URL(rssURL);

        SyndFeedInput input = new SyndFeedInput();
        SyndFeed feed = input.build(new XmlReader(feedUrl));

        List entries = feed.getEntries();
        for (Object entry : entries) {
            SyndEntryImpl syndEntry = (SyndEntryImpl) entry;
            String title = syndEntry.getTitle();
            String htmlDesc = syndEntry.getDescription().getValue();
            EpisodeInfo episode = new EpisodeInfo(title);
            model.addElement(episode);
        }
    }

    class EpisodeInfo {

        private String title;
        private Date airDate;

        EpisodeInfo(String title) {
            this.title = title;

            //parse air date from title
            //date is in the format of [ dd-mmm-yyyy ]
            Matcher matcher = airDatePattern.matcher(title);
            if(matcher.find()) {
                String strDate = matcher.group(1);
                try {
                    airDate = DATE_FORMAT.parse(strDate);
                } catch (ParseException e) { /*nothing airDate will be null*/}
            }
        }

        public Date getAirDate() {
            return airDate;
        }

        public String getTitle() {
            return title;
        }

    }

    public static void main(String[]args){
        try {
            new MyEpisodesView(null).readSource();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FeedException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    class EpisodeTitleCellRenderer implements ListCellRenderer {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            if(value instanceof EpisodeInfo) {
                EpisodeInfo episode = (EpisodeInfo) value;
                JLabel jLabel = new JLabel(episode.getTitle());
                if(episode.getAirDate() != null) {
                    if( calendar.getTimeInMillis() > episode.getAirDate().getTime() ) {
                        jLabel.setForeground(Color.BLACK);
                    } else {
                        jLabel.setForeground(Color.lightGray);
                    }
                }
                return jLabel;
            }
            return null;
        }
    }

//    public void reloadData() {
//        init();
//    }
}
